import os, string
from stat import ST_MODE
#from types import IntType
IntType = type(0)

PLUS  = '+'
MINUS = '-'
ACCESS_VAL   = { 'r': 4, 'w': 2, 'x': 1 }
ACCESSOR_POS = { 'u': 0100, 'g': 010, 'o': 01, 'a': 0111 }

def mode(path):
	return os.stat(path)[ST_MODE] & 0777

def chmod(path, mod): 
	if type(mod) == IntType:
		os.chmod(path, mod)
		return
	chmodarg = mode(path)
	for m in string.split(mod):
		try:
			sign = PLUS
			i = string.index(m,sign)
		except ValueError:
			sign = MINUS
			try: i = string.index(m,MINUS)
			except ValueError:
				return -1
		left  = m[:i]
		right = m[i+1:]
		accval = 0
		for accestype in right:
			accval = accval + ACCESS_VAL[accestype]
		modval = 0
		for accessor in left:
			modval = modval + ACCESSOR_POS[accessor] * accval
		if sign == PLUS:
			chmodarg = chmodarg | modval
		else:
			chmodarg = chmodarg & ~modval
	os.chmod(path, chmodarg)



if __name__ == '__main__':
	cwd = os.getcwd()
	m = mode(cwd); print 'Current mode ',oct(m)
	chmod(cwd, 'u-w'); print 'User without write permission ',oct(mode(cwd))
	chmod(cwd, 'ugo+rwx') ; print 'All permissions to everyone ',oct(mode(cwd))
	chmod(cwd, 'ug-x o-rwx'); print 'User,group without x-perm, other no perm ',oct(mode(cwd))
	chmod(cwd, m); print 'Reset to old mode ', oct(mode(cwd))
